package com.sparkseries.service.impl;

import com.sparkseries.common.security.domain.SecurityUser;
import com.sparkseries.common.util.tool.ObjectConvertTool;
import com.sparkseries.dao.SysAuthMapper;
import com.sparkseries.dao.SysUserMapper;
import com.sparkseries.domain.SysAuth;
import com.sparkseries.domain.SysUser;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 自定义登录校验
 */
@Service
public class JdbcUserDetailsServiceImpl implements UserDetailsService, UserDetailsPasswordService {
    @Resource
    private SysUserMapper userMapper;
    @Resource
    private SysAuthMapper authMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (Objects.nonNull(username)) {
            // 根据username获取SysUser
            SysUser user = userMapper.getUserByUsername(username);
            if (user == null) {
                return null;
            }
            SecurityUser sysUser = ObjectConvertTool.originConvert(user, SecurityUser.class);

            // 根据userId获取roleIds
            List<Long> roleIds = userMapper.getRoleIdsByUserId(sysUser.getId());
            // 根据roleId获取auth
            List<SysAuth> auths = authMapper.getAuthByRoleId(roleIds);
            if (!auths.isEmpty()) {
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();

                for (SysAuth auth : auths) {
                    SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + auth.getAuthName());
                    authorities.add(authority);
                }

                sysUser.setAuthorities(authorities);

                return sysUser;
            }
        }
        return null;
    }

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        Integer result = userMapper.updatePasswordByUsername(user.getUsername(), newPassword);

        if (result == 1) {
            ((SecurityUser) user).setPassword(newPassword);
        }
        return user;
    }
}
